package vip.hamlin.net.task;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.alidns.model.v20150109.DescribeDomainRecordsRequest;
import com.aliyuncs.alidns.model.v20150109.DescribeDomainRecordsResponse;
import com.aliyuncs.alidns.model.v20150109.UpdateDomainRecordRequest;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.StringUtils;
import vip.hamlin.net.Utils.HttpUtils;
import vip.hamlin.net.Utils.Utils;
import vip.hamlin.net.Utils.ValidateUtils;
import vip.hamlin.net.bean.NetCommonBean;

import java.io.IOException;
import java.util.List;

/**
 * task
 * Created by SunShao on 2016/6/24.
 */
@SuppressWarnings("unused")
@Configuration
@EnableAsync
@EnableScheduling
public class UpdateDnsTask {
    @Autowired
    private NetCommonBean netCommonBean;
    private IAcsClient client = null;


    @Scheduled(cron = "${cron_expression}")
    public void updateDns() throws IOException {
        String currentIP = getCurrentIP();
        if (!StringUtils.isEmpty(currentIP)) {
            System.out.println(Utils.getCurrentTime() + " current ip is : " + currentIP);
            // 请求net获取当前subdomain的ip
            DescribeDomainRecordsResponse.Record record = getSubDoaminRecord();
            updateDnsRecordIp(currentIP, record);
        } else {
            System.out.println(Utils.getCurrentTime() + " get current ip failed!");
        }
    }

    private void updateDnsRecordIp(String currentIP, DescribeDomainRecordsResponse.Record record) {
        String subDoaminIp = record.getValue();
        System.out.println("subDomain ip is : " + subDoaminIp);
        if (currentIP.equals(subDoaminIp)) {
            System.out.println("current ip == subDoamin ip");
        } else {
            if (updateRecordIp(currentIP, record)) {
                System.out.println("update dns success!");
            } else {
                System.out.println("update dns failed!");
            }
        }
    }

    private boolean updateRecordIp(String currentIP, DescribeDomainRecordsResponse.Record record) {
        UpdateDomainRecordRequest request = new UpdateDomainRecordRequest();
        request.setActionName("UpdateDomainRecord");
        request.setRecordId(record.getRecordId());
        request.setRR(netCommonBean.getSubDomain());
        request.setType("A");
        request.setValue(currentIP);
        HttpResponse response = null;
        try {
            response = buildClient().doAction(request);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        if (200 == response.getStatus())
            return true;
        return false;
    }


    private String getCurrentIP() {
        String result = HttpUtils.doGet(netCommonBean.getCurrentIpUrl());
        if (!ValidateUtils.isIp(result)) {
            return null;
        }
        return result;
    }

    public DescribeDomainRecordsResponse.Record getSubDoaminRecord() {
        DescribeDomainRecordsRequest request = new DescribeDomainRecordsRequest();
        request.setActionName("DescribeDomainRecords");
        request.setDomainName(netCommonBean.getDomainName());
        request.setAcceptFormat(FormatType.JSON);
        request.setMethod(MethodType.POST);

        DescribeDomainRecordsResponse response = null;
        try {
            response = buildClient().getAcsResponse(request);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        if (response != null) {
            List<DescribeDomainRecordsResponse.Record> domainRecords = response.getDomainRecords();
            for (DescribeDomainRecordsResponse.Record record : domainRecords) {
                if (record.getRR().equals(netCommonBean.getSubDomain())) {
                    return record;
                }
            }
        }
        return null;
    }

    public IAcsClient buildClient() {
        if (client != null)
            return client;
        String regionId = "cn-hangzhou"; //必填固定值，必须为“cn-hanghou”
//        String accessKeyId = "LBDZ0mVBgExTLPLK"; // your accessKey
//        String accessKeySecret = "H8S8DIB8jNwGeDqKR4y3S1038dqu7k";// your accessSecret
        IClientProfile profile = DefaultProfile.getProfile(regionId, netCommonBean.getAccessKeyID(), netCommonBean.getAccessKeySecret());
        // 若报Can not find endpoint to access异常，请添加以下此行代码
        // DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", "Alidns", "alidns.aliyuncs.com");
        client = new DefaultAcsClient(profile);
        return client;
    }
}
